<template>
	<view class="customer-management">

		<!-- <view class="search-bar">
			<u-search placeholder="搜索网点/用户名称" shape="round" :border="false" bg-color="#f5f7fa"></u-search>
		</view> -->

		<!-- 主体布局：左侧树形筛选 + 右侧列表 -->
		<view class="layout">
			<!-- 左侧：树形银行-网点筛选（所有节点默认展开） -->
			<view class="left-filter">
				<tree-select :tree-data="bankTree" @node-select="handleNodeSelect"></tree-select>
			</view>

			<!-- 右侧：人员列表 与之前一致 -->
			<view class="right-list">
				<template v-if="userList.length > 0">
					<view v-for="(user, index) in userList" :key="user.id" class="user-item"
						:class="{ active: index === hoverIndex }" @click="selectUser(user)"
						@touchstart="hoverIndex = index" @touchend="hoverIndex = -1">
						<view class="user-avatar" :style="{ backgroundColor: user.avatar }"></view>
						<view class="user-info">
							<text class="user-name">{{ user.nickName }} @{{ user.dept.deptName }}</text>
						</view>
					</view>
				</template>
				<template v-else>
					<view class="empty-tip">暂无相关人员</view>
				</template>
			</view>
		</view>

		<!-- 转移确认弹窗 与之前一致 -->
		<u-popup v-model="transferDialogShow" mode="center" width="70%">
			<view class="dialog-content">
				<text class="dialog-title">转移</text>
				<text class="dialog-desc">确认进行转让吗？转让后需对方确认</text>
				<view class="dialog-btns">
					<u-button type="default" @click="transferDialogShow = false" class="dialog-btn">取消</u-button>
					<u-button type="primary" @click="confirmTransfer" class="dialog-btn">确认</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	// 树形选择组件（递归渲染）
	import TreeSelect from './component/TreeSelect.vue';
	import {
		JzzxTasks,
		JzzxTasksuserList
	} from '@/common/api/renwu.js'
	export default {
		components: {
			TreeSelect
		},
		data() {
			return {
				// 树形结构数据：包含银行、网点层级，isExpanded: true 表示默认展开
				bankTree: [],
				userList: [],
				hoverIndex: -1,
				transferDialogShow: false,
				currentTransferUser: null,
				selectedNode: null // 存储当前选中的树形节点
			}
		},
		onLoad() {
			this.getData()
		},
		methods: {
			navigateBack() {
				uni.navigateBack();
			},
			async getData() {
				try {
					const res = await JzzxTasks();
					console.log(res, '树形数据');

					// 格式化树形数据（补充 level、isLeaf、isExpanded）
					const formatTree = (list, level) => {
						return list.map(item => {
							const hasChildren = item.children && item.children.length > 0;
							return {
								...item,
								level: level || 0,
								isExpanded: true, // 默认展开
								isLeaf: !hasChildren, // 无子集则为叶子节点
								children: hasChildren ? formatTree(item.children, level + 1) : []
							};
						});
					};

					// 格式化数据并赋值
					this.bankTree = formatTree(res.data, 0);

					// 自动选中第一个节点（加载其人员列表）
					if (this.bankTree.length > 0) {
						const firstNode = this.bankTree[0];
						// 如果第一个节点是叶子节点，直接选中；否则选中其第一个子节点（如果有）
						const targetNode = firstNode.isLeaf ? firstNode : (firstNode.children?.[0] || firstNode);
						this.handleNodeSelect(targetNode); // 触发选中逻辑
					}
				} catch (error) {
					console.error('获取树形数据失败', error);
				}
			},
			async loadUserList(id) {
				uni.showLoading({
					title: '加载中...'
				});
				try {
					const param = {
						personnelType: 1,
						deptId: id
					};
					const res = await JzzxTasksuserList(param);
					this.userList = res.data || []; // 确保为数组（避免null/undefined）

					// 若数据为空，可提示（也可通过UI展示）
					if (this.userList.length === 0) {
						// uni.showToast({ title: '暂无相关人员', icon: 'none', duration: 1500 });
					}
				} catch (error) {
					console.error('加载人员列表失败', error);
					this.userList = []; // 错误时置空，显示空状态
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			// 树形节点选中回调
			handleNodeSelect(node) {
				this.selectedNode = node;
				console.log('选中节点：', node);
				// 实际场景：根据选中的网点加载对应人员列表
				this.loadUserList(node.deptId);
			},
			selectUser(user) {
				// this.currentTransferUser = user;
				// this.transferDialogShow = true;
				console.log(user, 'user')
				// 获取当前页面栈
				const pages = getCurrentPages();
				// 上一页索引 = 当前页索引 - 1
				const prevPage = pages[pages.length - 2];
				// 直接修改上一页的数据（修改的是上一页的 data 中的 transferPersons）
				prevPage.$data.transferPersons = [user];

				// 返回上一页
				uni.navigateBack({
					delta: 1
				});
			},
			confirmTransfer() {
				uni.showToast({
					title: `确认转移 ${this.currentTransferUser.name}`,
					icon: 'none'
				});
				this.transferDialogShow = false;
			}
		}
	};
</script>



<style scoped lang="scss">
	/* 页面样式与之前一致，补充左侧树形筛选的容器样式 */
	.left-filter {
		width: 240rpx;
		background-color: #fff;
		border-right: 1rpx solid #eee;
		padding: 0;
		overflow-y: auto; // 树形结构过长时可滚动
		max-height: calc(100vh - 160rpx); // 与主体布局高度一致
	}

	.customer-management {
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.search-bar {
		padding: 16rpx 30rpx;
		background-color: #fff;
	}

	.layout {
		display: flex;
		height: calc(100vh - 160rpx); // 减去导航和搜索栏高度
	}

	.left-filter {
		width: 200rpx;
		background-color: #fff;
		border-right: 1rpx solid #eee;
		padding: 20rpx 0;
	}

	.filter-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		cursor: pointer;
	}

	.filter-label {
		font-size: 28rpx;
		color: #333;
	}

	.bank-list,
	.branch-list {
		background-color: #fff;
	}

	.bank-item,
	.branch-item {
		padding: 20rpx 30rpx;
		font-size: 26rpx;
		color: #666;
	}

	.bank-item.active,
	.branch-item.active {
		background-color: #f0f9ff;
		color: #0057b8;
		font-weight: 500;
	}

	.right-list {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
	}

	.user-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 8rpx;
		padding: 24rpx;
		margin-bottom: 16rpx;
		cursor: pointer;
	}

	.user-item.active {
		background-color: #f0f0f0;
	}

	.user-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.user-name {
		font-size: 28rpx;
		color: #333;
	}

	.dialog-content {
		padding: 30rpx;
		text-align: center;
	}

	.dialog-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 20rpx;
	}

	.dialog-desc {
		font-size: 26rpx;
		color: #666;
		display: block;
		margin-bottom: 30rpx;
	}

	.dialog-btns {
		display: flex;
		justify-content: space-between;
	}

	.dialog-btn {
		flex: 1;
		margin: 0 10rpx;
	}

	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>